#include "VertexArray.h"

VertexArray::VertexArray()
{
	GLCall(glGenVertexArrays(1, &m_RendererID));
}

VertexArray::~VertexArray()
{	
	GLCall(glDeleteVertexArrays(1, &m_RendererID));
}

void VertexArray::AddBuffer(const VertexBuffer& vb, const VertexBufferLayout& layout)
{
	Bind();	// 绑定VertexBuffer之前，一定要先绑定VAO！！！
	vb.Bind();
	unsigned int offset = 0;
	const auto& elements = layout.GetElements();
	for (int index = 0; index < elements.size(); ++index)
	{
		const auto& ele = elements[index];
		GLCall(glVertexAttribPointer(index, ele.count, ele.type, ele.normalized, layout.GetStride(), 
			(const void*)(offset)));
		GLCall(glEnableVertexAttribArray(index));
		offset += ele.count * VertexBufferElement::GetSizeOfType(ele.type);
	}
}

void VertexArray::Bind() const
{
	GLCall(glBindVertexArray(m_RendererID));
}

void VertexArray::Unbind() const
{
	GLCall(glBindVertexArray(0));
}
